<?php
/**
 * OutsourceOffer.php
 * Author: luoji (867404364@qq.com)
 * Date: 2020-12-19
 * Time: 13:59
 */

namespace App\Http\Controllers\Api\Customer;


use App\Exceptions\RunException;
use App\Http\Controllers\Base;
use App\Tables;

class OutsourceOffer extends Base
{
    public function get()
    {

        $oid = (int) $this->request->get('oid', 0);
        if($oid <= 0) {
            return $this->responseSuccess();
        }
        $outsource = Tables\Outsource::find($oid);
        if(empty($outsource)) {
            return $this->responseSuccess();
        }

        $allB = Tables\Business::all();
        $offerList = Tables\OutsourceOffer::where('oid', $oid)->get();
        $r = [];

        foreach($allB as $b) {
            $rr =  [
                'id' => $b['id'],
                'name' => $b['name'],
                'pyCode' => $b['py_code'],
                'price' => 0
            ];
            foreach ($offerList as $of) {
                if($b['id'] == $of['bid']) {
                    $rr = [
                        'id' => $b['id'],
                        'name' => $b['name'],
                        'pyCode' => $b['py_code'],
                        'price' => $of['price']
                    ];
                    break;
                }
            }
            $r[] = $rr;
        }
        return $this->responseSuccess($r);
    }

    public function save()
    {
        $oid = (int) $this->request->post('oid', 0);
        $list = (array) $this->request->post('list', []);
        if($oid<=0 or empty($list)) {
            return $this->responseFail();
        }
        \DB::beginTransaction();
        try {
            $addTime = time();
            $outsource = Tables\Outsource::find($oid);
            if(empty($outsource)) {
                throw new RunException('未找到信息');
            }
            $insertData = [];
            $delId = [];
            foreach($list as $v) {
                $insertData[] = [
                    'oid' => $oid,
                    'bid' => $v['id'],
                    'price' => (double) $v['price'],
                    'add_time' => $addTime
                ];
                $delId[] = $v['id'];
            }

            Tables\OutsourceOffer::where('oid' , $oid)->whereIn('bid', $delId)->delete();

            $ok = (bool) Tables\OutsourceOffer::insert($insertData);
            if(!$ok) { throw new RunException('修改失败(2)'); }
            \DB::commit();
        } catch (RunException $e) {
            \DB::rollBack();
            return $this->responseFail($e->getMessage());
        } catch (\Exception $e) {
            \DB::rollBack();
            return $this->responseFail('数据库错误');
        }
        return $this->responseSuccess();
    }
}